<?php
namespace app\admin\controller\admin\goods;
use app\admin\model\Goods;
use app\admin\model\GoodsAttr;
use app\admin\model\GoodsClassification;
use app\admin\model\GoodsPictures;
class GoodsAdd extends \app\admin\controller\admin\BaseAdmin{ 
    public function index(){
        //编辑商品模式下
        $request = \think\Request::instance();
        //接收商品的id
        $goods_id = $request->get('goods_id');
        if($goods_id){
            $goods = new Goods();
            //查询该管理员管理的商品        
            $goods->where('admin_id',$this->adminData['id']);
            //根据商品的id查询数据
            $goods->where('id',$goods_id);
            $item = $goods->find();
            if(!$item){
                $this->error('无效的商品ID！');
            }
            //预设标题名称
            $item_title = '编辑商品';
            //根据商品id查询商品相关的数据
            //查询商品的属性
            $item_attr = $item->goodsAttr;
            //查询商品的分类
            $item_classification = $item->goodsClassification;
            //查询商品的详细图片
            $item_pictures = $item->goodsPictures;            
        }else{
            //添加商品的模式下设置默认值 stdClass是空对象 "\"代表没有命名空间
            $item = new \stdClass;
            $item_title = '添加商品';
            $item->id = 0;
            $item->title = '';
            $item->description = '';
            $item->content = '';
            $item_classification = new \stdClass;
            $item_classification->category = '';
            $item_classification->taste = '';
            $item_classification->features = '';
            $item_classification->size = '';
            $item_attr = new \stdClass;
            $item_attr->price = '';
            $item_attr->market_price = '';
            $item_attr->stock_number = '';
            $item_attr->status = '';
            $item_pictures = [];            
        }

        $data = [];
        //将查询结果传递给模板
        $data['item'] = $item;
        $data['item_title'] = $item_title;
        $data['item_attr'] = $item_attr;
        $data['item_classification'] = $item_classification;
        $data['item_pictures'] = $item_pictures;
        return view('admin/goods/goodsAdd',$data);
    }
    public function save(){
        $goods = new Goods();
        //接收从客户端提交过来的数据
        $request = \think\Request::instance();
        //在编辑模式下接收隐藏表单传过来的商品id,添加模式下商品的id默认为0
        $goods_id = $request->post('goods_id');
        //在编辑模式下
        if($goods_id > 0){
            //查询该管理员管理的商品        
            $goods->where('admin_id',$this->adminData['id']);
            //根据商品的id查询数据
            $goods->where('id',$goods_id);
            $goods = $goods->find();
            if(!$goods){
                $this->error('无效的商品ID！');
            }            
        }        
        $data = [
            'title' => $request->post('goods_title'),
            'category' => $request->post('goods_category'),
            'taste' => $request->post('goods_taste'),
            'features' => $request->post('goods_features'),
            'size' => $request->post('goods_size'),
            'price' => $request->post('goods_price'),
            'market_price' => $request->post('goods_market_price'),
            'stock_number' => $request->post('goods_stock_number'),
            'description' => $request->post('goods_description'),
            'status' => $request->post('goods_status'),
            'content' => $request->post('goods_content'),
        ];
        //从客户端传过来的类别、口味、特色、规格的值有可能为0
        if($data['category'] == 0 || $data['taste']  == 0 || $data['features'] == 0 || $data['size'] == 0){
            $this->error('请选择商品分类！',"admin/admin.goods.GoodsAdd/index?goods_id=$goods_id");
        }
        //定义验证规则
        $rules = [
            'title|商品标题' =>'require',
            'category|类别' =>'require',
            'taste|口味' =>'require',
            'features|特色' =>'require',
            'size|规格' =>'require',
            'price|商品价格' =>'require|number',
            'market_price|市场价格' =>'require|number',
            'stock_number|库存数量' =>'require|number|\d+',
            'description|商品简介' =>'require',
            'status|商品状态' =>'require',
            'content|商品介绍' =>'require',
        ];
        //实例化验证器对象
        $validate = new \think\Validate($rules);
        //对数据进行验证
        if(!$validate->check($data)){
            //显示错误信息
            $this->error($validate->getError());
        }

        //无论是添加模式还是编辑模式都需要的共同部分
        //将数据插入表中
        $goods->admin_id = $this->adminData->id;
        $goods->title = $data['title'];
        $goods->description = $data['description'];
        $goods->content = $data['content'];
        //更新数据的时候，返回的结果$is为更新了多少条数据的数量，一条数据没有更新就是0，有一条更新就是1
        //添加数据的时候，插入成功$is就是true失败为false
        $is = $goods->allowField(true)->save();
        //只有在添加模式下显示失败信息
        if($goods_id <1 && !$is){
            return $this->error('商品入库失败！');
        }

        $goods_attr = new GoodsAttr();          
        //编辑模式下
        if($goods_id > 0){
            $goods_attr = $goods_attr->where('goods_id',$goods_id)->find();       
        }else{
            //添加模式下
            //把商品id插入到商品属性表中
            //$goods->id是商品的id
            $goods_attr->goods_id = $goods->id;            
        }

        //无论是编辑模式还是添加模式都需要的共同部分
        //将数据插入商品属性表中
        $goods_attr->price = $data['price'];
        $goods_attr->market_price = $data['market_price'];
        $goods_attr->stock_number = $data['stock_number'];
        $goods_attr->status = $data['status'];
        $is = $goods_attr->allowField(true)->save();
        if($goods_id <1 && !$is){
            return $this->error('商品属性入库失败！');
        }

        $goods_classification = new GoodsClassification();
        //编辑模式下
        if($goods_id > 0){
            $goods_classification = $goods_classification->where('goods_id',$goods_id)->find();
        }else{
            //添加模式下
            //把商品的id插入到商品分类表中
            $goods_classification->goods_id = $goods->id;
        }
        //不管是添加模式还是编辑模式都需要的共同部分
        $goods_classification->category = $data['category'];
        $goods_classification->taste = $data['taste'];
        $goods_classification->features = $data['features'];
        $goods_classification->size = $data['size'];
        $is = $goods_classification->allowField(true)->save();
        //添加模式下
        if($goods_id <1 && !$is){
            return $this->error('商品分类入库失败！');
        }

        //添加模式下的商品id
        if($goods_id < 1){
            //这里的商品id从添加模式下插入商品表的时候取出来的
            $goods_id = $goods->id;
        }
        //接收多文件上传的值
        $files = request()->file('goods_files');
        //调用处理商品图片上传的类方法，$msg的值为goodsImgUpload()返回的值
        $msg = $this->goodsImgUpload($files,$goods_id);
        //显示成功信息，并跳转网页
        return $this->success($msg,'admin/admin.goods.GoodsList/index');
    }
    /*
    商品图片的上传
     */
    public function goodsImgUpload($files,$goods_id){        
        //上传失败的图片记录到这里
        $errors = [];
        //标记商品主图是否更新过
        $image_status = false;
        //循环上传
        foreach($files as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate([
                    'size'=>1024*1024*10,
                    'ext'=>'jpg,png,gif'
                    ])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info === false){
                // 把错误信息保存到数组中
                $errors[] = $file->getError();
            }else{
                //图片上传成功就把图片写入PcGoodsPictures数据库中
                $image = [
                    'goods_id' =>$goods_id,
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    'path' =>$info->getSaveName(),
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    'pic_name' =>$info->getFilename(),  
                    // 输出 jpg
                    'ext' =>$info->getExtension(),              
                ];
                //实例化商品图片的数据库
                $goods_pictures = new GoodsPictures();                
                $is = $goods_pictures->allowField(true)->save($image);
                if(!$is){
                    return $this->error('商品图片入库失败！');
                }  
                //实现只把上传图片的第一张图片作为商品主图
                if(!$image_status){
                    //将商品主图插入goods表中
                    $goods = new Goods();
                    $goods = $goods->where('id',$goods_id)->find();
                    $goods->image = $info->getSaveName();
                    $goods->allowField(true)->save();
                    $image_status = true;
                } 
                //**********对图像进行裁剪********
                //文件所在文件夹(硬盘路径)
                $path = ROOT_PATH . 'public' . DS . 'uploads' . DS;
                //原图路径
                $fullpath = $path . $image['path']; 
                //裁剪之后图的路径(在原图的基础上增加了原图的后缀名)
                $savepath = $path . $image['path'].".".$image['ext'];
                //生成略缩图
                $image = \think\Image::open($fullpath); 
                // 按照原图的比例居中裁剪生成一个最大为263*230的缩略图，图片名为原图名+后缀名
                $image->thumb(263, 230,\think\Image::THUMB_CENTER)->save($savepath);
            }   
        }
        //编写提示信息
        $msg = "商品发布成功,";
        //计算错误信息数组中有多少数据
        $error_number = count($errors);
        if($error_number > 0){
            $msg .= "有{$error_number}图片未上传成功！其它上传成功！";
        }else{
            $msg .= "所有文件上传成功！";
        }
        return $msg;        
    }
    /*
    对html编辑器上传图片的处理
     */
    public function uploadImg(){
        $request = \think\Request::instance();
        $simditor_files = $request->file('simditor_files');
        //对html编辑器图片的默认值设置
        $result = [
            'success'=>false,
            'msg' => '',
            'file_path' => '',
        ];
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $simditor_files->validate([
                'size'=>1024*1024*10,
                'ext'=>'jpg,png,gif'
                ])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info === false){
            // 上传失败获取错误信息
            $result['msg'] = $simditor_files->getError();
            return $result;
        }           
        $result['success'] = true;
        //获取图片的相对路径,并且将相对路径传值到公共文件up_url()函数中
        $result['file_path'] = up_url($info->getSaveName());
        return $result;
    }
    //商品编辑模式下处理商品详情图片的删除
    public function imageDel(){
        $request = \think\Request::instance();
        //接收商品id
        $goods_id = $request->get('goods_id');
        //接收图片id
        $image_id = $request->get('image_id');
        $goods = new Goods();
        //查询该管理员管理的商品        
        $goods->where('admin_id',$this->adminData['id']);
        //根据商品的id查询数据
        $goods->where('id',$goods_id);
        $item = $goods->find();
        if(!$item){
            $this->error('无效的商品ID！');
        }
        $goods_pictures = new GoodsPictures();
        //查询该商品对应的图片        
        $goods_pictures->where('goods_id',$goods_id);
        //根据商品图片的id查询出要删除的图片
        $goods_pictures->where('id',$image_id);
        $item = $goods_pictures->find();
        if(!$item){
            $this->error('无效的商品图片ID！');
        }
        //对商品图片进行逻辑删除 在数据库中修改is_delete字段为1代表删除
        $is = $item->save(['is_delete' => 1]);
        if($is){
            $this->success('删除图片成功！');
        }
    }
}
